package com.throttle.raildroid;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

public class Throttle {
	private boolean bell = false;
	private boolean horn  = false;
	private boolean light  = false;
	private boolean dir  = false;
	private boolean connected = false;
	private OutputStream out = null;
	private Socket mysocket = null;
	
	public boolean connect(String host, int port){
		try {
			this.mysocket = new Socket();
			InetAddress addr = InetAddress.getByName(host);
			SocketAddress sockaddr = new InetSocketAddress(addr, port);
			int timeoutMs = 15000;   // 15 seconds
			this.mysocket.connect(sockaddr, timeoutMs);
			out = mysocket.getOutputStream();
		} catch (UnknownHostException e) {
			//System.out.println("Unknown Host Error in Throttle Connection\n");
			return false;
		}catch (SocketTimeoutException e) {
			return false;
		}catch (IOException e) {
			//System.out.println("IO Error in Connection\n");
			return false;
		}
		this.connected = true;
		return true;
	}
	
	public boolean controlTrain(int trainAddress){
		if(!connected)
		{
			return false;
		}
		try{
			byte[] msg = JavaRail.makeControlTrain(trainAddress);
			out.write(msg);
			return true;
		}catch (java.net.UnknownHostException u) {
            return false;
        }
        catch (java.io.IOException e) {
            return false;
        }
	}
	
	public boolean setTrainSpeed(int slot,int speed){
		if(!connected)
		{
			return false;
		}
		try{
			byte[] msg = JavaRail.makeSetSpeed(slot, speed);
			out.write(msg);
			return true;
		}catch (java.net.UnknownHostException u) {
            return false;
        }
        catch (java.io.IOException e) {
            return false;
        }
	}
	
	public boolean setSwitchState(int switchNumber, boolean state)
	{
		if(!connected)
		{
			return false;
		}
		try{
			byte[] msg = JavaRail.makeChangeSwitch(switchNumber, state);
			out.write(msg);
			return true;
		}catch (java.net.UnknownHostException u) {
            System.out.println("uhe!"); // Display the string.
            System.err.println(u);
            return false;
        }
        catch (java.io.IOException e) {
            System.out.println("ioex!"); // Display the string.
            System.err.println(e);
            return false;
        }
	}
	
	public boolean setLight(int slow, boolean state){
		return true;
	}
	
}
